package com.aerozhonghuan.logisticsmall.framework.hybrid.actions;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.webkit.WebBackForwardList;

import com.aerozhonghuan.logisticsmall.framework.hybrid.NewWebviewFragment;
import com.aerozhonghuan.logisticsmall.framework.hybrid.SimpleActionHandler;
import com.aerozhonghuan.logisticsmall.framework.hybrid.bean.JsMobileAgentConstants;
import com.aerozhonghuan.hybrid.XJsCallback;
import com.aerozhonghuan.hybrid.XWebView;

import org.json.JSONObject;

/**
 * 描述
 * 作者 Zhang Yonghui
 * 创建日期 2019/1/21
 */
public class JumpToHistoryActionHandler extends SimpleActionHandler {
    private static final String KEY_URL = "history";

    public JumpToHistoryActionHandler(NewWebviewFragment fragment) {
        super(JsMobileAgentConstants.FLAG_JUMPTOHISTORY, fragment);
    }

    @Override
    public void handleAction(@NonNull String action, @Nullable JSONObject params, @Nullable XJsCallback callBack) {
        if (params == null) {
            return;
        }
        String historyUrl = params.optString(KEY_URL);
        XWebView webView = getFragment().getWebView();
        WebBackForwardList webBackForwardList = webView.copyBackForwardList();
        for (int i = 0; i < webBackForwardList.getSize(); i++) {
            if (TextUtils.equals(historyUrl, webBackForwardList.getItemAtIndex(i).getOriginalUrl())) {
                webView.goBackOrForward(i);
                int back = i - webBackForwardList.getCurrentIndex();
                if (webView.canGoBackOrForward(back)) {
                    webView.goBackOrForward(back);
                }
            }
        }
    }
}
